package ug.co.icom.kyazze.healthticket;

import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import ug.co.icom.kyazze.healthticket.DataBase.Database;
import ug.co.icom.kyazze.healthticket.data.Allergy;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.DatePicker;
import android.widget.EditText;

public class AllergyDataInput extends Activity {
	private EditText text_allergy_name;
	private EditText text_diagnosis;
	private EditText text_severity;
	private EditText text_reaction;
	private EditText text_comments;
	private EditText text_occurence;
	Database query_handler;
	static final int DATE_DIALOG_ID = 0;

	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		int cyear = c.get(Calendar.YEAR);
		int cmonth = c.get(Calendar.MONTH);
		int cday = c.get(Calendar.DAY_OF_MONTH);
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, cyear, cmonth,
					cday);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		// onDateSet method
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			String date_selected = String.valueOf(dayOfMonth) + " /"
					+ String.valueOf(monthOfYear + 1) + " /"
					+ String.valueOf(year);
			// Toast.makeText(getApplicationContext(),
			// "Selected Date is ="+date_selected, Toast.LENGTH_SHORT).show();
			text_diagnosis.setText(date_selected);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_allergy_entry_form);
		createOrOpenDB();
		text_allergy_name = (EditText) findViewById(R.id.text_allergy_name);
		text_diagnosis = (EditText) findViewById(R.id.text_diagnosis);
		text_severity = (EditText) findViewById(R.id.text_severity);
		text_reaction = (EditText) findViewById(R.id.text_reaction);
		text_occurence = (EditText) findViewById(R.id.text_occurence);
		text_comments = (EditText) findViewById(R.id.text_comments);

		text_diagnosis.setOnTouchListener(new OnTouchListener() {
			@SuppressWarnings("deprecation")
			public boolean onTouch(View v, MotionEvent event) {
				if (v == text_diagnosis)
					showDialog(DATE_DIALOG_ID);
				return false;
			}
		});

	}

	@SuppressLint("SimpleDateFormat")
	public void postNewAllergy(final View view) {

		SQLiteDatabase db = openOrCreateDatabase("mrDB", MODE_PRIVATE, null);
		Database database = new Database(db);

		Allergy allergy_obj = new Allergy();

		allergy_obj.setAllergy_name(text_allergy_name.getText().toString());

		// converting text string to date
		SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
		Date date;
		try {
			date = formatter.parse(text_diagnosis.getText().toString());
			allergy_obj.setAllergy_date_of_diagnosis(date);
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}

		allergy_obj.setAllergy_severity(text_severity.getText().toString());
		allergy_obj.setAllergy_reaction(text_reaction.getText().toString());
		allergy_obj.setAllergy_occurence(text_occurence.getText().toString());
		allergy_obj.setAllergy_additional_comments(text_comments.getText()
				.toString());
		allergy_obj.setIS_Synced("false");
		database.insertAllergy(allergy_obj);
		// allergy_data.insert_allergy(allergy_obj);
		db.close();

		Intent i = new Intent(getApplicationContext(), AllergyListNames.class);
		startActivity(i);

	}

	public void postNewAllergy2(final View view) throws Exception {

		new RetreiveFeedTask().execute("");

		// Intent i = new Intent(getApplicationContext(),
		// PHRElementsList.class);
		// startActivity(i);

	}

	class RetreiveFeedTask extends AsyncTask<String, Void, String> {

		@SuppressWarnings("unused")
		private Exception exception;

		protected String doInBackground(String... urls) {
			try {
				URL url = new URL(
						"https://api.mongohq.com/databases/mHealth/collections/medical_records/documents/5298bae2fd9358dfc60001b3?_apikey=YPXfSPrBkC5EMptf7m6pxSlB3B2AcRUc6Mk7mWuPO0");
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setRequestMethod("PUT");
				connection.setDoOutput(true);
				connection.setRequestProperty("Content-Type",
						"application/json");
				connection.setRequestProperty("Accept", "application/json");
				String a_name = text_allergy_name.getText().toString();
				String a_date = text_diagnosis.getText().toString();
				String a_severity = text_severity.getText().toString();
				String a_reaction = text_reaction.getText().toString();
				String a_occurence = text_occurence.getText().toString();
				String a_comments = text_comments.getText().toString();

				OutputStreamWriter osw = new OutputStreamWriter(
						connection.getOutputStream());

				String query = String
						.format("{\"document\" : { \"$addToSet\" : {\"allergies\" : {\"name\" : \"%s\" , \"date_of_diagnosis\" : \"%s\", \"severity\" : \"%s\", \"reaction\" : \"%s\", \"occurence\" : \"%s\", \"additional_comments\" : \"%s\" }} }}",
								a_name, a_date, a_severity, a_reaction,
								a_occurence, a_comments);
				osw.write(query);
				osw.flush();
				osw.close();

				System.err.println(connection.getResponseCode());
			} catch (Exception e) {
				this.exception = e;
				return null;
			}
			return null;
		}

	}

	private void createOrOpenDB() {
		SQLiteDatabase db = openOrCreateDatabase("mrDB", MODE_PRIVATE, null);
		Database database = new Database(db);
		database.createOrOpenDB();

	}

}
